package pos.data;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.csvreader.CsvWriter;

import pos.domain.Address;

public class CSVAddressDAO implements IAddressDAO {

	private CsvWriter openFile() {

		CsvWriter csvOutput = null;
		String outputFile = "data/address.csv";

		// before we open the file check to see if it already exists
		boolean alreadyExists = new File(outputFile).exists();

		try {
			// use FileWriter constructor that specifies open for appending
			csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');

			// if the file didn't already exist then we need to write out the
			// header line
			if (!alreadyExists) {
				csvOutput.write("OID");
				csvOutput.write("city");
				csvOutput.write("email");
				csvOutput.write("fax");
				csvOutput.write("phone");
				csvOutput.write("name");
				csvOutput.write("street");
				csvOutput.write("zipcode");
				csvOutput.endRecord();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return csvOutput;

	}

	private void closeFile(CsvWriter writer) {
		writer.close();

	}

	public void delete(String addressOID) {

	}

	public void insert(String addressOID, Address a) {
        
    	CsvWriter writer = this.openFile();
  	
    	try {
    		writer.write(addressOID);
			writer.write(a.getCity());
		   	writer.write(a.getEmail());
		   	writer.write(a.getFax());
		   	writer.write(a.getPhone());    	
		   	writer.write(a.getName());
		   	writer.write(a.getStreet());
		   	writer.write(String.valueOf(a.getZipcode()));
		   	writer.endRecord();
    	} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    	closeFile(writer);
    }

	public Address select( String addressOID) {
		return null;
	//TODO
		
	}
}
